﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Mani.Common.Security;
using RastinArgham.CRM.Business;

namespace RastinArgham.CRM.Web
{
    public partial class errors_list : System.Web.UI.Page
    {
        public ISecurityManager securityManager { get; set; }
        public CRMRepository crmRepository { get; set; }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (securityManager == null)
            {
                securityManager = new SecurityManager();
                securityManager.authProvider = new WebAuthorizationProvider();
            }

            if (crmRepository == null)
                crmRepository = new CRMRepository();


            if (!securityManager.IsActionPermitted("errors_list"))
                Response.Redirect("~/access_denied.aspx");

            if (!Page.IsPostBack)
                FindErrorLogs();
        }

        protected void gvErrors_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvErrors.PageIndex = e.NewPageIndex;
            FindErrorLogs();
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            FindErrorLogs();
        }

        private void FindErrorLogs()
        {
            gvErrors.DataSource = crmRepository.FindErrorLogs(txtUsername.Text);
            gvErrors.DataBind();

            divDetails.Visible = false;
        }

        protected void gvErrors_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {
            int errorId = Convert.ToInt32(gvErrors.DataKeys[e.NewSelectedIndex].Value);
            ErrorLog error = crmRepository.GetErrorLogById(errorId);

            if (error == null)
                return;

            lblExceptionDetail.Text = error.ExceptionDetails;
            lblUserAgent.Text = error.UserAgent;
            divDetails.Visible = true;
        }
    }
}